import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bilibili/core/model/video_model.dart';
import 'package:flutter_bilibili/ui/pages/video_play/dan_mu_2/dan_mu_proto.dart';
import 'package:flutter_bilibili/ui/pages/video_play/video/video_play_comments.dart';
import 'package:flutter_bilibili/ui/pages/video_play/video/video_play_profile.dart';
import 'package:flutter_bilibili/ui/pages/video_play/video/video_play_initialize_item.dart';
import 'package:flutter_bilibili/ui/shared/app_theme.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:video_player/video_player.dart';

import '../../../../core/model/feed_index_model.dart';
import '../../../../core/model/video_reply_model.dart';
import '../../../../core/service/request/video_reply_request.dart';
import '../../../widgets/bilibili_controls.dart';

class HYVideoPlayContent extends StatefulWidget {
  FeedIndexItem video;
  double aspectRatio;

  HYVideoPlayContent({required this.video, required this.aspectRatio});

  @override
  State<HYVideoPlayContent> createState() => _HYVideoPlayContentState();
}

class _HYVideoPlayContentState extends State<HYVideoPlayContent> {
  var tabTitle = ['简介', '评论'];

  ///视频播放
  late VideoPlayerController _videoPlayerController;
  late ChewieController _chewieController;
  bool isLoadingAccomplished = false;
  int allCount = -1;
  late HYVideoReplyModel videoReply;
  late int leftCount;

  @override
  void initState() {
    ///视频初始化
    _videoPlayerController =
        VideoPlayerController.network(widget.video.videoData);
    _videoPlayerController.initialize().then((value) {
      _chewieController = ChewieController(
        allowMuting: false,
        videoPlayerController: _videoPlayerController,
        autoPlay: true,
        customControls: HYBilibiliControls(
          video: widget.video,
        ),
      );
      isLoadingAccomplished = true;
      if (mounted) {
        setState(() {});
      }
    });

    // ///隐藏顶部的状态栏
    // SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
    //     overlays: [SystemUiOverlay.bottom]);

    ///获取视频回复的评论
    HYVideoReplyRequest.getVideoReply(widget.video.args!.aid!, 1, 1)
        .then((value) {
      allCount = value.cursor.allCount;
      videoReply = value;
      leftCount = allCount - videoReply.replies.length;
      if (mounted) {
        setState(() {});
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // double width = MediaQuery.of(context).size.width;
    return DefaultTabController(
      length: tabTitle.length,
      initialIndex: 0,
      child: Scaffold(
        body: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            buildVideoPlayVideoPlayer(),
            buildVideoPlayTabBar(),
            Expanded(
              child: buildVideoPlayTabBarView(),
            )
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _videoPlayerController.dispose();
    _chewieController.dispose();

    ///推出视频播放界面就将顶部状态栏加上
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
        overlays: [SystemUiOverlay.top, SystemUiOverlay.bottom]);
    super.dispose();
  }

  ///leading
  Widget buildVideoPlayLeading() {
    return IconButton(
        onPressed: () {
          Navigator.of(context).pop();
        },
        icon: Image.asset(
          "assets/image/icon/back_custom.png",
          width: videoPlayIconSize,
          height: videoPlayIconSize,
        ));
  }

  ///TabBarView
  Widget buildVideoPlayTabBarView() {
    return TabBarView(
      children: tabTitle.map((e) {
        if (e == "简介") {
          return Container();

          ///视频简介
          // return HYVideoPlayProfile(
          //   video: widget.video,
          //   oldVideo: widget.oldVideo,
          // );
        } else {
          if (allCount == -1) {
            return const Center(
              child: CircularProgressIndicator(
                color: HYAppTheme.norMainThemeColors,
              ),
            );
          } else {
            ///评论
            return HYVideoPlayComments(
              videoReply: videoReply,
              aid: widget.video.args!.aid!,
              leftCount: leftCount,
            );
          }
        }
      }).toList(),
    );
  }

  ///TabBar
  PreferredSizeWidget buildVideoPlayTabBar() {
    return PreferredSize(
      ///tab设置底色
      preferredSize: Size.fromHeight(5.h),
      child: Material(
        color: Colors.white,
        child: Container(
          decoration: BoxDecoration(
              border: BorderDirectional(
                  bottom: BorderSide(
                      color: HYAppTheme.norGrayColor.withOpacity(.2)))),
          child: TabBar(
            tabs: tabTitle.map((e) {
              if (allCount > 0 && e.contains("评论")) {
                return Tab(text: "$e $allCount");
              } else {
                return Tab(text: e);
              }
            }).toList(),
            indicatorColor: HYAppTheme.norMainThemeColors,
            unselectedLabelColor: HYAppTheme.unselectedLabelColor,
            labelColor: HYAppTheme.norMainThemeColors,
            indicatorSize: TabBarIndicatorSize.label,
            labelStyle: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: HYAppTheme.xxSmallFontSize),
            unselectedLabelStyle: TextStyle(
                fontWeight: FontWeight.normal,
                fontSize: HYAppTheme.xxSmallFontSize),
            indicatorWeight: 2.h,
            labelPadding: EdgeInsets.zero,
            indicatorPadding: const EdgeInsets.only(bottom: 6).r,
          ),
        ),
      ),
    );
  }

  ///Action
  List<Widget> buildVideoPlayActions() {
    return [
      IconButton(
          onPressed: () => print("mini_window_custom"),
          icon: Image.asset(
            "assets/image/icon/mini_window_custom.png",
            width: videoPlayIconSize,
            height: videoPlayIconSize,
          )),
      IconButton(
          onPressed: () => print("tv_play_custom"),
          icon: Image.asset(
            "assets/image/icon/tv_play_custom.png",
            width: videoPlayIconSize,
            height: videoPlayIconSize,
          )),
      IconButton(
          onPressed: () => print("video_player_more_custom"),
          icon: Image.asset(
            "assets/image/icon/video_player_more_custom.png",
            width: videoPlayIconSize,
            height: videoPlayIconSize,
          )),
    ];
  }

  ///视频和弹幕
  Widget buildVideoPlayVideoPlayer() {
    double width = MediaQuery.of(context).size.width;
    return isLoadingAccomplished == true
        ? Container(
            padding: EdgeInsets.zero,
            color: HYAppTheme.norTextColors,
            alignment: Alignment.topCenter,
            height: width /
                _chewieController.videoPlayerController.value.aspectRatio,
            child: Stack(
              children: [
                Chewie(
                  controller: _chewieController,
                ),

                /// 忽略弹幕的点击事件，将点击传递给视频
                IgnorePointer(
                  child: BuildDanMuProtoScreen(
                    width: width,
                    oid: widget.video.playerArgs!.aid!,

                    ///转为多少分钟，整除
                    duration: widget.video.playerArgs!.duration! ~/ 60,
                  ),
                )
              ],
            ),
          )
        : Container(
            height: width / 1.77777777777777777,
            color: HYAppTheme.norTextColors,
            child: Center(
              child: SizedBox(
                width: 40.w,
                height: 40.h,
                child: const CircularProgressIndicator(
                  color: HYAppTheme.norMainThemeColors,
                ),
              ),
            ),
          );
  }
}
